<?php
error_reporting(1);

require ("imdbsearch.class.php");

$movtypes	= array("mov","avi","mpg","mpeg","divx","ogm","mp4","mkv");	// What are movie file extensions
$startdir	= getcwd();

$forcexml		= false;											// Force creation of XML files, even if already existing
$forcecover		= false;											// Force creation of cover files, even if already existing
$repaircover	= false;											// Repair cover symlinks (unlink + new symlink)
$getsubs		= false;											// Get subtitles for the movies

while(count($argv) > 2){
	if(substr($argv[1],0,1) == "-"){
		switch(substr($argv[1],1)){
			case "x":	// Force recreate xml files
			case "xml":
				echo "Force re-download of XML files = ON\n";
				$forcexml = true;
				break;
			case "c":
			case "cover":
				echo "Force re-download of cover files = ON\n";
				$forcecover = true;
				break;
			case "rc":
			case "repaircover":
				echo "Force remake of cover symlinks = ON\n";
				$repaircover = true;
				break;
			case "ws":
			case "withsubs":
				echo "Subtitle downloads (in development)\n";
				$getsubs = true;
				break;
			case "md":
			case "makedir":
				echo "Make genre and year directories\n";
				$makedirs = true;
				break;
		}
		array_splice($argv, 1, -1*(count($argv)-2));
	}
}


if(isset($argv[1])){ // Directory is given
	$subdirname = $argv[1];

	$imdbnr		= 0;
	$filesize	= 0;
	$xml		= array();
	$xmlfile	= false;
	$cover		= false;
	$subtitles	= false;
	$listavi	= array();
	$listavism	= array();
	$sample		= "";
	$trailer	= "";
	$movcount	= 0;
	$xmlcount	= 0;
	$jpgcount	= 0;
	$srtcount	= 0;
	$nfofile	= "";

		$temp = explode("/",$subdirname);
		$movie = $temp[count($temp)-2];
		$movie   = preg_replace("/\s*?\(.*/","",$subdirname);		// Remove everything after first bracket (year, rip type, ...)
		if(file_exists($subdirname."/movietitle.txt")){	// Cached real title
			$temp	= file($subdirname."/movietitle.txt");
			$movie	= trim($temp[0]);
		}

		if(file_exists($subdirname."/imdbnr.txt")){		// Cached IMDB nr
			$temp	= file($subdirname."/imdbnr.txt");
			$imdbnr	= trim($temp[0]);
		}else{
			$search = new imdbsearch();
			$search->setsearchname ($name);
			$results = $search->results();
			foreach ($results as $res) {
				if(strtolower($res->title()) == strtolower($name)){
					$imdbnr = $res->imdbid();
					break;
				}
			}

			$imdbnr	= $temp[0];
			if($imdbnr > 0){
				$temp	= fopen($subdirname."/imdbnr.txt","w");
				fwrite($temp, $imdbnr);
			}
		}
		
	echo $imdbnr;
	exit;
}


exit;




		printf(" %7s |", $imdbnr);
		
		$subdir = opendir($subdirname."/");
		while(false !== ($file = readdir($subdir))){
			if(substr($file,0,1) == "."){ continue; }				// No hidden files / dirs
			$ext = strtolower(substr($file, strrpos($file, ".")+1));
			if($ext == ""){ continue; }
			if(in_array($ext, $movtypes)){							// It is a movie
				$movcount++;
				if(strpos($file, "samp") > 0){						// It is a sample
					$sample = $file;
				}elseif(strpos($file, "trailer") > 0){				// It is a trailer
					$trailer = $file;
				}else{												// It is a part of the movie
					array_push($listavism, substr($file, 0, strrpos($file, ".")));
					array_push($listavi, $file);
					if($filesize == 0){								// Get file size of first movie, for subtitle downloading...
						$filesize = filesize($subdirname."/".$file);
					}
				}
			}elseif(strpos($file, ".xml") > 0){						// It is a xml data file
				$xmlfile = true;
				$xmlcount++;
			}elseif($file == "cover.jpg"){							// It is a (folder) cover
				$cover = true;
			}elseif($ext == "jpg"){									// Other JPG file, consider it to be symlink to cover
				$jpgcount++;
			}elseif(($ext == "srt") or ($ext == "sub")){			// We have subtitles...
				$srtcount++;
				$subtitles = true;
			}elseif($ext == "nfo"){									// We have more info...
				$nfofile = $file;
			}
		}
		printf(" %3s |", count($listavi));

		if($imdbnr > 0){

			if((!$xmlfile) or $forcexml or ($xmlcount < $movcount)){
				$xml = file("http://movies.tegosaurus.com/atvfilesimdbxml.php?id=".$imdbnr);
				sort($listavi);
				$i = 0;
				foreach($listavi as $avi){
					$i++;
					$ext = strtolower(substr($avi, strrpos($avi, ".")+1));
					if(count($listavi) > 1){
						$txml = str_replace("</title>"," / Part ".$i."</title>", implode("",$xml));
					}else{
						$txml = implode("",$xml);
					}
					$x = fopen($subdirname."/".str_replace(".".$ext,".xml",$avi),"w");
					fwrite($x, $txml);
				}
				if($sample != ""){
					$ext = strtolower(substr($sample, strrpos($sample, ".")+1));
					$txml = str_replace("</title>"," / Sample</title>", implode("",$xml));
					$x = fopen($subdirname."/".str_replace(".".$ext,".xml",$sample),"w");
					fwrite($x, $txml);
				}
				if($trailer != ""){
					$ext = strtolower(substr($trailer, strrpos($trailer, ".")+1));
					$txml = str_replace("</title>"," / Trailer</title>", implode("",$xml));
					$x = fopen($subdirname."/".str_replace(".".$ext,".xml",$trailer),"w");
					fwrite($x, $txml);
				}
				echo "  +  |";
			}else{
				echo "  1  |";
			}
			

			if($repaircover){
				chdir($startdir."/".$subdirname."/");
				foreach($listavi as $avi){
					$ext = strtolower(substr($avi, strrpos($avi, ".")));
					if(file_exists(str_replace($ext,".jpg",$avi))){
						unlink(str_replace($ext,".jpg",$avi));
					}
					if($cover){
						symlink("cover.jpg",str_replace($ext,".jpg",$avi));
					}
				}
				if($sample != ""){
					$ext = strtolower(substr($sample, strrpos($sample, ".")+1));
					if(file_exists(str_replace(".".$ext,".jpg",$sample))){
						unlink(str_replace(".".$ext,".jpg",$sample));
					}
					if($cover){
						symlink("cover.jpg",str_replace(".".$ext,".jpg",$sample));
					}
				}
				if($trailer != ""){
					$ext = strtolower(substr($trailer, strrpos($trailer, ".")+1));
					if(file_exists(str_replace(".".$ext,".jpg",$trailer))){
						unlink(str_replace(".".$ext,".jpg",$trailer));
					}
					if($cover){
						symlink("cover.jpg",str_replace(".".$ext,".jpg",$trailer));
					}
				}
			}


			if((!$cover) or $forcecover){
				$coverf = file("http://movies.tegosaurus.com/images/".$imdbnr.".jpg");
				if($coverf != false){
					$h = fopen($subdirname."/cover.jpg","w");
					fwrite($h, implode("",$coverf));
					chdir($startdir."/".$subdirname);
					foreach($listavi as $avi){
						$ext = strtolower(substr($avi, strrpos($avi, ".")+1));
						symlink("cover.jpg",str_replace(".".$ext,".jpg",$avi));
					}
					if($sample != ""){
						$ext = strtolower(substr($sample, strrpos($sample, ".")+1));
						symlink("cover.jpg",str_replace(".".$ext,".jpg",$sample));
					}
					if($trailer != ""){
						$ext = strtolower(substr($trailer, strrpos($trailer, ".")+1));
						symlink("cover.jpg",str_replace(".".$ext,".jpg",$trailer));
					}
					echo "  +  |";
				}else{
					if($cover)    { echo "  1  |"; }else{ echo "  0  |"; }
				}
			}elseif($jpgcount < $movcount){
				chdir($startdir."/".$subdirname);
				foreach($listavi as $avi){
					$ext = strtolower(substr($avi, strrpos($avi, ".")+1));
					symlink("cover.jpg",str_replace(".".$ext,".jpg",$avi));
				}
				if($sample != ""){
					$ext = strtolower(substr($sample, strrpos($sample, ".")+1));
					symlink("cover.jpg",str_replace(".".$ext,".jpg",$sample));
				}
				if($trailer != ""){
					$ext = strtolower(substr($trailer, strrpos($trailer, ".")+1));
					symlink("cover.jpg",str_replace(".".$ext,".jpg",$trailer));
				}
				echo "  x  |";
			}else{
				echo "  1  |";
			}
			
			
			if($getsubs and !$subtitles){
				$file = implode("",file("http://www.opensubtitles.org/en/search/subsumcd-".count($listavi)."/sublanguageid-dut/moviebytesize-".$filesize."/imdbid-".$imdbnr."/subformat-srt/xml"));
				$dom = new DomDocument();
				$dom->loadXML($file);
				$subtitles = $dom->getElementsByTagName("subtitle");
				$found = false;
				$maxscores = 0;
				foreach($subtitles as $sub){
					$dl = $sub->getElementsByTagName("SubDownloadsCnt")->item(0)->textContent;
					if($dl > $maxscores){
						$bestshot = $sub;
						$dlsub = $sub;
						$maxscores = $dl;
						$found = true;
					}
				}
				if(!$found){
					$file = implode("",file("http://www.opensubtitles.org/en/search/subsumcd-".count($listavi)."/sublanguageid-dut/imdbid-".$imdbnr."/subformat-srt/xml"));

					$dom = new DomDocument();
					$dom->loadXML($file);
					$subtitles = $dom->getElementsByTagName("subtitle");
					$found = false;
					$maxscores = 0;

					$temp = "";
					if($nfofile != ""){
						$temp = implode("",file($subdirname."/".$nfofile));
					}elseif(file_exists($subdirname."/relname.txt")){
						$temp = implode("",file($subdirname."/relname.txt"));
					}

					foreach($subtitles as $sub){
						$mytemp = $sub->getElementsByTagName("MovieReleaseName");
						foreach($mytemp as $rlnm){
							$relname = $rlnm->textContent;

							if($temp != ""){
								if((strlen($relname) > 2) and (strpos(strtolower($temp), strtolower($relname)))){
									$dl = $sub->getElementsByTagName("SubDownloadsCnt")->item(0)->textContent;
									if($dl > $maxscores){
										$bestshot = $sub;
										$dlsub = $sub;
										$maxscores = $dl;
										$found = true;
//											echo "OK, found at line 286\n";
									}
								}
							}
						}

						if(!$found){
							$mytemp = $sub->getElementsByTagName("SubAuthorComment");
							foreach($mytemp as $rlnm){
								$relname = $rlnm->textContent;

								if($temp != ""){
									if((strlen($relname) > 2) and (strpos(strtolower($temp), strtolower($relname)))){
										$dl = $sub->getElementsByTagName("SubDownloadsCnt")->item(0)->textContent;
										if($dl > $maxscores){
											$bestshot = $sub;
											$dlsub = $sub;
											$maxscores = $dl;
											$found = true;
//											echo "OK, found at line 304\n";
										}
									}
								}
							}
						}
						
					}

					
					if(!$found){
						// Go to every found subtitles page and check for filenames...
						// Will be slow...
						foreach($subtitles as $sub){
							$sl = $sub->getElementsByTagName("IDSubtitle");
							
							foreach($sl as $sll){
								$suburl  = $sll->getAttribute("Link");
								$subpage = implode("",file("http://www.opensubtitles.org".$suburl."/xml"));
// echo "\nhttp://www.opensubtitles.org".$suburl."/xml\n";
								$subdom = new DomDocument();
								$subdom->loadXML($subpage);
								$files = $subdom->getElementsByTagName("SubActualCD");

								$sf = array();
								foreach($files as $file){
									array_push($sf, $file->getAttribute("SubFileName"));
								}
								sort($sf);
								sort($listavism);

								foreach($sf as $sfile){
									if(in_array(substr($sfile, 0, strrpos($sfile, ".")), $listavism)){
										$bestshot = $sub;
										$found = true;
										$dlsub = $sub;
//										echo "OK, found at line 340\n";
									}
								}
							}
						}
					}

				}

				if($found){
					$dll = $dlsub->getElementsByTagName("IDSubtitle");
					foreach($dll as $dls){
//						if(!$dls->hasChildNodes()){ continue; }
//						$dl = $dls->item(0)->getAttribute("DownloadLink");
						$dl = $dls->getAttribute("DownloadLink");
//						echo "Downloading subtitles: zip file is available at http://www.opensubtitles.org".$dl."\n";

						$temp = implode("",file("http://www.opensubtitles.org".$dl));
						$h = fopen("/tmp/subtitle.zip","w");
						fwrite($h, $temp);

						$zip = array();
						// exec("unzip -nj '".$_POST["target_dir"]."/".$filenameserver."' -d $datadir$temp",$feedback);
						exec("unzip -nj /tmp/subtitle.zip -x 'subtitles.nfo' -d '".$startdir."/".$subdirname."/'", $zip);
						$temp = array();
						$zip = preg_grep("/\.srt/",$zip);
						$srtfiles = array();
						foreach($zip as $line){
							$matches = array();
							if(preg_match("/.+?\s\/mnt.+\/(.+)/", $line, $matches)){
								array_push($srtfiles, $matches[1]);
							}
						}
					
						sort($srtfiles);
						for($i=0;$i<count($srtfiles);$i++){
							rename($startdir.'/'.$subdirname."/".$srtfiles[$i], $startdir.'/'.$subdirname."/".str_replace(substr($listavi[$i],strrpos($listavi[$i],".")),".srt",$listavi[$i]));
						}
						echo "  +  |";
					}
				}else{
					echo "  0  |";
				}
			}else{
				if($subtitles){ echo "  1  |"; }else{ echo "  0  |"; }
			}

			if($trailer != ""){ echo "  1  |"; }else{ echo "  0  |"; }
					
			
		}else{
			if($xmlfile)  { echo "  1  |"; }else{ echo "  0  |"; }
			if($cover)    { echo "  1  |"; }else{ echo "  0  |"; }
			if($subtitles){ echo "  1  |"; }else{ echo "  0  |"; }
			if($trailer != ""){ echo "  1  |"; }else{ echo "  0  |"; }
		}
		echo "\n";
	}
	echo "|----------------------------------------+---------+-----+-----+-----+-----+-----|\n";
	echo "| Movie Title                            |  IMDB   | AVI | XML | CVR | SUB | TLR |\n";
	echo "+----------------------------------------+---------+-----+-----+-----+-----+-----+\n\n";
	
	if($makedirs){
		exec("/usr/local/php5/bin/php makedirs.php Alphabetical .");
	}

}else{
	echo "\nUsage:\n";
	echo "  php autograbber.php [options] <basedir>\n";
	echo "\nOptions: \n";
	echo "  -x  :  Force new XML file creation\n";
	echo "  -c  :  Force new cover download\n";
	echo "  -rc :  Repair covers\n";
	echo "  -ws :  Grab subtitles (Dutch) from opensubtitles.org\n";
	echo "\n\n";
}

?>